package cn.tianyun.pethome.login.service.impl;

import cn.tianyun.pethome.basic.exception.BusinessException;
import cn.tianyun.pethome.basic.util.BaseConstants;
import cn.tianyun.pethome.basic.util.loginUtil.MD5Utils;
import cn.tianyun.pethome.basic.util.loginUtil.StrUtils;
import cn.tianyun.pethome.login.domain.RegisterVo;
import cn.tianyun.pethome.login.service.RegisterService;
import cn.tianyun.pethome.org.domain.User;
import cn.tianyun.pethome.org.mapper.UserMapper;
import cn.tianyun.pethome.org.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
   private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    @Override
    public void registerUser(RegisterVo registerVo) {
        if(registerVo.getMobile()==null){
            throw  new BusinessException("手机号不能为空");
        }
        if(registerVo.getPassword()==null){
            throw  new BusinessException("密码不能为空");
        }
        if(registerVo.getPasswordTo()==null){
            throw  new BusinessException("请再次确认密码");
        }
        if(registerVo.getPasswordTo()==registerVo.getPassword()){
            throw  new BusinessException("两次密码输入不一致，请重新输入");
        }
        String phoneCodeKey=registerVo.getMobile()+BaseConstants.ImgCode.STATE_REGISTER;

        Object o = redisTemplate.opsForValue().get(phoneCodeKey);
        System.out.println(o.toString());
        System.out.println(registerVo.getPhoneCode());
        if(o.toString()==null){
            throw new BusinessException("验证码已过期,请重新获取");
        }
        if(!o.toString().equals(registerVo.getPhoneCode())){
            throw new BusinessException("验证码不正确，请重新输入");
        }
        System.out.println("------------");
        User user = new User();
        user.setAge(0);
        user.setPhone(registerVo.getMobile());
        user.setUsername(registerVo.getMobile());
        user.setCreatetime(new Date());
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(registerVo.getPassword() + salt);
        user.setPassword(password);
        user.setSalt(salt);
        user.setState(BaseConstants.User.STATE_USER);
        userService.add(user);
    }

}
